package com.hiwan.unions.activity.main.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.hiwan.unions.R;
import com.hiwan.unions.activity.main.CityActivity;
import com.hiwan.unions.activity.main.fragment.base.RootFragment;
import com.hiwan.unions.application.ConstantsValues;
import com.hiwan.unions.application.javaScript.AndroidJavaScript;
import com.hiwan.unions.application.request.ConstsNet;
import com.hiwan.unions.util.Utils;
import com.hiwan.unions.util.interfaces.LoginInterface;
import com.hiwan.unions.view.NavigationView;
import com.hiwan.unions.view.ProgressWebView;
import com.hiwan.unions.view.PullToRefreshLayout;
import com.jwenfeng.library.pulltorefresh.ViewStatus;
import com.yanzhenjie.nohttp.Logger;

/**
 * Created by llg on 2017/6/7.
 */
public class EventWebFragment extends RootFragment implements LoginInterface {
    private ProgressWebView myWebView;
    private AndroidJavaScript javaScript;
    private ProgressBar myProgressBar;
    private int currentProgress;
    private boolean isAnimStart = false;
    private PullToRefreshLayout pullToRefreshLayout;
    private NavigationView navigationView;

    @Override
    public int getLayout() {
        canLoadMore = false;
        canRefresh = false;
        return R.layout.fragment_eve_web;
    }

    private void getDate() {
        myWebView.loadUrl(Utils.Urls2(ConstsNet.LuckDraw, userInfoC, userInfo));
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (myWebView != null) {
            myWebView.removeAllViews();
            myWebView.destroy();
        }
    }

    @Override
    protected void Interface() {
        super.Interface();
        pullToRefreshLayout = findView(R.id.pullToRefreshLayout);
        pullToRefreshLayout.setCanLoadMore(canLoadMore);
        pullToRefreshLayout.setCancanRefresh(canRefresh);
        navigationView = findView(R.id.navigationView);
        navigationView.getGoBackBtn().setVisibility(View.INVISIBLE);

        javaScript = new AndroidJavaScript(getActivity());
        javaScript.setLoadingListener(this);

        myWebView = findView(R.id.myWebView);
        myProgressBar = findView(R.id.myProgressBar);
        myProgressBar.setVisibility(View.VISIBLE);
        myProgressBar.setAlpha(1.0f);
        myProgressBar.setMax(100);
        myWebView
                .addJavascriptInterface(javaScript, "Android");
        myWebView.setWebViewClient(webviewcilnt);
        myWebView.setWebChromeClient(we);
        View view6 = findView(R.id.RelaButtonTitlenear);
        // 当SDK版本号为19以上版本时
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (null != view6) {
                view6.setVisibility(View.VISIBLE);
            }
        }
    }

    private void City() {
        Intent intent = new Intent();
        intent.setClass(getActivity(), CityActivity.class);
        startActivityForResult(intent, 0);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Logger.i("hidden" + hidden);
        if (hidden) {
        } else {
            getDate();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onStop() {
        super.onStop();
    }


    public void getRespStatuss(String title) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            if (title.contains("404") || title.contains("403") || title.contains("500") || title.contains("Error")) {
            }
        }
    }


    public void cityName() {
        myWebView.loadUrl("javascript:getCityName('" + userInfoC.getString(ConstantsValues.CITYNAMEOne, "") + "')");
    }

    @Override
    public void getCityInfo() {
        Logger.i("执行？？？getCityInfo");
        myWebView.quickCallJs("getCityInfo", userInfoC.getString(ConstantsValues.CITYNAMECODE, ""), userInfoC.getString(ConstantsValues.CITYNAME, ""), userInfoC.getString(ConstantsValues.CITYNAMEOneCode, ""), userInfoC.getString(ConstantsValues.CITYNAMEOneCode, ""));
    }

    @Override
    public void LoginIntent() {

    }


    @Override
    public void TitleTextView(final boolean type) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                if (type) {
//                    layout_fragmnt_nearby.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
//                } else {
//                    layout_fragmnt_nearby.setBackgroundColor(Color.argb((int) 0, 255, 255, 255));
//                }
            }
        });
    }


    private void noWebview() {
        navigationView.getNavigationTitleTxt().setText("网络连接失败");
        showError();
    }

    /**
     * 网络显示错误
     */
    protected void showError() {
        // 结束刷新
        pullToRefreshLayout.showView(ViewStatus.ERROR_STATUS);
        View error = pullToRefreshLayout.getView(ViewStatus.ERROR_STATUS);
        findView(error, R.id.shuax).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navigationView.getNavigationTitleTxt().setText("普惠活动");
                getDate();
            }
        });
    }

    public WebViewClient webviewcilnt = new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            //这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
            noWebview();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            myProgressBar.setVisibility(View.VISIBLE);
            myProgressBar.setAlpha(1.0f);
        }

        @TargetApi(android.os.Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            if (request.isForMainFrame()) { // 或者： if(request.getUrl().toString() .equals(getUrl()))
                noWebview();
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    };
    public WebChromeClient we = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            currentProgress = myProgressBar.getProgress();
            if (newProgress >= 100 && !isAnimStart) {
                // 防止调用多次动画
                isAnimStart = true;
                myProgressBar.setProgress(newProgress);
                // 开启属性动画让进度条平滑消失
                startDismissAnimation(myProgressBar.getProgress(), myProgressBar);
            } else {
                // 开启属性动画让进度条平滑递增
                startProgressAnimation(newProgress, myProgressBar);
            }
        }

        //配置权限（同样在WebChromeClient中实现）
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                                                       GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            getRespStatuss(title);
        }
    };

    public void startProgressAnimation(int newProgress, ProgressBar myProgressBar) {
        ObjectAnimator animator = ObjectAnimator.ofInt(myProgressBar, "progress", currentProgress, newProgress);
        animator.setDuration(300);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.start();
    }

    /**
     * progressBar消失动画
     */
    public void startDismissAnimation(final int progress, final ProgressBar myProgressBar) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(myProgressBar, "alpha", 1.0f, 0.0f);
        anim.setDuration(1500);  // 动画时长
        anim.setInterpolator(new DecelerateInterpolator());     // 减速
        // 关键, 添加动画进度监听器
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float fraction = valueAnimator.getAnimatedFraction();      // 0.0f ~ 1.0f
                int offset = 100 - progress;
                myProgressBar.setProgress((int) (progress + offset * fraction));
            }
        });

        anim.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                // 动画结束
                myProgressBar.setProgress(0);
                myProgressBar.setVisibility(View.INVISIBLE);
                isAnimStart = false;
            }
        });
        anim.start();
    }

    @Override
    protected void initData() {

    }
}
